package cqupt.spark_log.info;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cqupt.spark_log.contrant.Contant;
import cqupt.spark_log.entity.Task;
import cqupt.spark_log.fileio.FileReadMan;
import cqupt.spark_log.fileio.FileWriteMan;
import cqupt.spark_log.utils.ECUtil;

public class TableInfo {
	private BanchInfo banchInfo;
	private FileWriteMan fileWriteMan;
	public TableInfo(BanchInfo banchInfo) {
		this.banchInfo = banchInfo;
		this.fileWriteMan = new FileWriteMan();
	}
	public void saveTable() {
		Map<String,Task> tasks = this.banchInfo.getTasks();
		//拿到上一次计算的结果
		String path = Contant.BASE_PATH + "/" + Contant.APP_NAME+".old";
		File oldFile = new File(path);
		Map<String,String[]> map = new HashMap<String,String[]>();
		if (oldFile.exists()) {
			FileReadMan fileReadMan = new FileReadMan("/" + Contant.APP_NAME+".old",true);
			//跳过第一行
			if (fileReadMan.hasNext()) {
				fileReadMan.next();
			}
			while (fileReadMan.hasNext()) {
				String line = fileReadMan.next();
				if (!line.equals("")) {
					String[] lines = line.split(",");
					map.put(lines[0], lines);
				}
			}
		}
		//title是固定的
		String title = Contant.getTitle();
		String[] titleArray = title.split(",");
		fileWriteMan.insertLine(title);
		
		for (String key: tasks.keySet()) {
			Task task = tasks.get(key);
			String executorId = task.getExecutorId();
			int index = 1;
			for (;index < titleArray.length; index++) {
				if (executorId.equals(titleArray[index])) {
					break;
				}
			}
			StringBuilder stringBuilder = new StringBuilder(task.getJobId()+";"+task.getStageId()+";"+task.getIndex()+",");
			String taskKey = stringBuilder.substring(0, stringBuilder.length()-1);
			String[] energyTimeOldList = map.get(taskKey);
			for (int i=1 ;i < titleArray.length; i++) {
				String energyTimeOld = "0;0";
				if (energyTimeOldList != null) {
					energyTimeOld = energyTimeOldList[i];
				}
				if (i == index) {
					if (!"0;0".equals(energyTimeOld)) {
						String[] old = energyTimeOld.split(";");
						double energyOld = Double.parseDouble(old[0]);
						double timeOld = Double.parseDouble(old[1]);
						double energyAverage = (task.getEc()+energyOld)/2;
						double timeAverage = (task.getRunTime()+timeOld)/2;
						stringBuilder.append(ECUtil.get4point(energyAverage)+";"+ECUtil.get4point(timeAverage)+",");
					} else {
						stringBuilder.append(task.getEc()+";"+task.getRunTime()+",");
					}
				} else {
					stringBuilder.append(energyTimeOld+",");
				}
			}
			stringBuilder.deleteCharAt(stringBuilder.length()-1);
			fileWriteMan.insertLine(stringBuilder.toString());
		}
	}
}
